﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ATEGo
{
    //———————————————————————【1加载文件】————————————————————————
    /// <summary>
    /// 初始化执行器的一些参数
    /// 对所有线程来说是公有的
    /// </summary>
    public partial class InitialExecutor
    {
        public IExecutorForm This_Form;
        public InitialExecutor(IExecutorForm form1)
        {
            This_Form = form1;
        }

        /// <summary>
        /// ATEGo的配置 Configuration.js
        /// </summary>
        public ATEGo_Configuration CFG { get; set; }
        /// <summary>
        /// 所有的OrderItem
        /// </summary>
        public Dictionary<string, OrderItem> AllOrderItems { get; set; }
        /// <summary>
        /// 类别，就是Order的文件名
        /// </summary>
        public List<string> OrderFileNameOnDisplay { get; set; }
        /// <summary>
        /// 根据类别，展示在界面供用户选择的OrderName
        /// </summary>
        public Dictionary<string,List<string>> NamesByOrderNameOnDisplay { get; set; }
        /// <summary>
        /// 根据类别，展示在界面供用户选择的OrderName的描述
        /// </summary>
        public Dictionary<string, List<string>> DesByOrderNameOnDisplay { get; set; }
        /// <summary>
        /// 核心路径，所有的路径都会基于此，必须以\\结尾
        /// </summary>
        public string CorePath { get; set; }
        /// <summary>
        /// 所有的CmdSuits文件，初始化会默认读取base命令集文件
        /// </summary>
        public DictCmdSuits Group_CmdSuits { get; set; }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="configurationPath"></param>
        public void P1_LoadFile(string configurationPath)
        {
            bool ret = true;
            //1读取Configuration.js文件
            ret = ReadJson_ATEGoConfiguration(configurationPath);
            if (!ret)
                return;
            //2读取所有order文件，并整合到Orders中。并给Orders_ShowName赋值
            ret = OrganizeOrders();
            if (!ret)
                return;
            //3读取默认的cmdSuit
            Group_CmdSuits = new DictCmdSuits(this);
        }
        /// <summary>
        /// 读取配置文件
        /// </summary>
        private bool ReadJson_ATEGoConfiguration(string path)
        {
            try
            {
                if (!File.Exists(path))
                    throw new FileNotFoundException("文件不存在");
                CFG = Json.Read<ATEGo_Configuration>(path);
                CorePath = Path.GetDirectoryName(path) + "\\";
                return true;
            }
            catch (Exception e)
            {
                MsgShow.Error(This_Form, "读取Configuration.json出现错误：" + e.Message);
                return false;
            }
        }
        /// <summary>
        /// 读取Order文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private Dictionary<string, OrderItem> ReadJson_Order(string path)
        {
            try
            {
                path = CorePath + path;
                if (!File.Exists(path))
                    throw new FileNotFoundException("文件不存在");
                return Json.Read<Dictionary<string, OrderItem>>(path);
            }
            catch (Exception e)
            {
                MsgShow.Error(This_Form, "读取Order出现错误：" + e.Message);
                return null;
            }
        }
        /// <summary>
        /// 读取所有order文件，并整合到Orders中。并给Orders_ShowName赋值
        /// </summary>
        /// <returns></returns>
        private bool OrganizeOrders()
        {
            try
            {
                AllOrderItems = new Dictionary<string, OrderItem>();
                NamesByOrderNameOnDisplay = new Dictionary<string, List<string>>();
                DesByOrderNameOnDisplay = new Dictionary<string, List<string>>();
                OrderFileNameOnDisplay = new List<string>();
                foreach (var p in CFG.OrderFiles)
                {
                    var thisJS = ReadJson_Order(p["path"].Trim());
                    //读取失败，立即返回
                    if (thisJS == null)
                        return false;
                    var thisName = p["name"].Trim();
                    if (p["display"].Trim().ToLower() == "true")
                    {
                        OrderFileNameOnDisplay.Add(thisName);
                    }
                    var lista = new List<string>();
                    var listb = new List<string>();
                    foreach (var item in thisJS)
                    {
                        AllOrderItems.Add(item.Key, item.Value);
                        //需要展示在界面的供用户选择的
                        if (p["display"].Trim().ToLower() == "true")
                        {
                            lista.Add(item.Key);
                            listb.Add(item.Value.description);
                        }
                    }
                    if (p["display"].Trim().ToLower() == "true")
                    {
                        NamesByOrderNameOnDisplay[thisName] = lista;
                        DesByOrderNameOnDisplay[thisName] = listb;
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                MsgShow.Error(This_Form, "Order整合出现错误：" + e.Message);
                return false;
            }
        }
    }

    /// <summary>
    /// 命令集字典，每一个是命令集
    /// </summary>
    public class DictCmdSuits : Dictionary<string, CmdSuits>
    {
        InitialExecutor initialExecutor;
        public DictCmdSuits(InitialExecutor initialExecutor) : base()
        {
            this.initialExecutor = initialExecutor;
            //默认加载base文件
            var temp = ReadJson_CmdSuits(initialExecutor.CFG.CmdSuits_NameToPath("$"));
            base["$"] = temp;
        }
        public new CmdSuits this[string CmdSuitName]
        {
            //懒加载CmdSuit
            get
            {
                CmdSuitName = CmdSuitName.Trim();
                if (!base.ContainsKey(CmdSuitName))
                {
                    var path = initialExecutor.CFG.CmdSuits_NameToPath(CmdSuitName);
                    var temp = ReadJson_CmdSuits(path);
                    if (temp != null)
                    {
                        base[CmdSuitName] = temp;
                    }
                    else
                    {
                        return null;
                    }
                }
                return base[CmdSuitName];
            }
        }

        /// <summary>
        /// 读取命令集
        /// </summary>
        /// <param name="path"></param>
        private CmdSuits ReadJson_CmdSuits(string path)
        {
            try
            {
                path = initialExecutor.CorePath + path;
                if (!File.Exists(path))
                    return null;
                return Json.Read<CmdSuits>(path);
            }
            catch (Exception e)
            {
                MsgShow.Error(initialExecutor.This_Form, "读取CmdSuits出现错误：" + e.Message);
                return null;
            }
        }
    }
}
